<script setup>
import { ref } from 'vue'
import axios from "@/utils/request.js";
import { trainSelectService } from '@/api/train';
import { userPageService } from "@/api/user.js";
import { titlePageService } from "@/api/title.js";
import { trainRecordAddService, trainRecordAddBatchService, trainRecordSelectService, trainRecordDeleteService, trainRecordModifyService } from "@/api/trainRecord.js";
import { trainRankAddService } from "@/api/trainRank.js";
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted } from "vue";

import { fileUploadService } from '@/api/file';
import { MdPreview } from 'md-editor-v3';
// import { MDEditor } from 'md-editor-v3';
// import {MdEditor} from 'md-editor-v3';
import 'md-editor-v3/lib/preview.css';
import moment from 'moment';
// 分页查询
const trainRecordInfo = ref([])
const selectIds = Array


const handleSelectionChange = (selection) => {
  selectIds.value = selection.map(item => item.recordId)
}

//分页查询底部导航栏
const pageNo = ref(1)
const pageSize = ref(10)
const trainRecordNameInput = ref()
const groupNameInput = ref()
const total = ref(0)

//页面加载的时候发送一次查询请求
onMounted(() => {
  load()
})
const handleCurrentChange = (val) => {
  pageNo.value = val
  load()
}
const handleSizeChange = (val) => {
  pageSize.value = val
  load()
}
const trainNameFuzzy = ref()
const userNameFuzzy = ref()
const titleNameFuzzy = ref()
const trains = ref([])
const users = ref([])
const titles = ref([])
//发送分页查询请求（包括搜索功能）
const load = async () => {
  //查询训练信息
  const res1 = await trainSelectService(1, 100000, '', '')
  trains.value = res1.data.data.list
  //查询队员信息
  const res2 = await userPageService(1, 100000, '', '', '')
  users.value = res2.data.data.list
  //查询题目信息
  const res3 = await titlePageService(1, 100000, '')
  titles.value = res3.data.data.list
  const res = await trainRecordSelectService(
    pageNo.value, pageSize.value, trainNameFuzzy.value, userNameFuzzy.value, titleNameFuzzy.value
  )
  if (res.data.status === 'success') {
    trainRecordInfo.value = res.data.data.list
    trainRecordInfo.value.forEach(item => {
      //更新所属队员和关联比赛
      item.trainName = trains.value.find(train => train.trainId == item.trainId)?.trainName || '未知训练';
      item.userName = users.value.find(user => String(user.userId) == String(item.userId))?.name || "未知用户";
      item.titleName = titles.value.find(title => title.titleId == item.titleId)?.titleName || '未知题目';
    })
    total.value = res.data.data.totalCount
  } else {
    ElMessage.error(res.data.info)
  }
}

/**
 * 添加训练记录信息
 */
//定义模态窗口变量和表格对象
const useTitles = ref(1)
const introduceModel = ref(false)
const showAddModal = ref(false)
const trainRecordInfoAddForm = ref({
  recordId: '',
  trainInfo: {
    trainId: '',
    trainName: ''
  },
  // trainId: '',
  userInfo: {
    userId: '',
    userName: ''
  },
  // titleInfo: {
  //   titleId: '',
  //   titleName: ''
  // }
  titleIds: ''
})
//  根据条件获取所有训练信息
const trainList = ref([])
const currenttrainName = ref()
const trainLoading = ref(false)
const handleInputTrainChange = (query) => {
  trainLoading.value = true;
  setTimeout(() => {
    loadtrain(query)
    trainLoading.value = false;
  }, 1000);
}
const loadtrain = async (name) => {
  const res = await trainSelectService(1, 100000, name, '')
  trainList.value = res.data.data.list
}
const changeTrain = (trainInfo) => {
  if (!trainInfo) return
  trainRecordInfoAddForm.value.trainInfo = trainInfo
}
//修改
const changeModifytrain = (trainInfo) => {
  if (!trainInfo) return
  trainRecordForm.value.trainInfo = trainInfo
}
//  根据条件获取所有队员信息
const userList = ref([])
const currentUserName = ref()
const userLoading = ref(false)
const handleInputUserChange = (query) => {
  userLoading.value = true;
  setTimeout(() => {
    loadUser(query)
    userLoading.value = false;
  }, 1000);
}
const loadUser = async (name) => {
  const res = await userPageService(1, 100000, '', name, '')
  userList.value = res.data.data.list
}
const changeUser = (userInfo) => {
  if (!userInfo) return
  trainRecordInfoAddForm.value.userInfo.userId = userInfo.userId
  trainRecordInfoAddForm.value.userInfo.userName = userInfo.name
}
const changeModifyUser = (userInfo) => {
  if (!userInfo) return
  trainRecordForm.value.userInfo.userId = userInfo.userId
  trainRecordForm.value.userInfo.userName = userInfo.name
}
//  根据条件获取所有老师信息
const titleList = ref([])
const currenttitleName = ref()
const titleLoading = ref(false)
const handleInputtitleChange = (query) => {
  titleLoading.value = true;
  setTimeout(() => {
    loadTitle(query)
    titleLoading.value = false;
  }, 1000);
}
const loadTitle = async (name) => {
  const res = await titlePageService(1, 100000, name)
  titleList.value = res.data.data.list
}
const changeTitle = (titleInfo) => {
  if (!titleInfo) return
  trainRecordInfoAddForm.value.titleIds = titleInfo
}
const changeModifytitle = (titleInfo) => {
  if (!titleInfo) return
  trainRecordForm.value.titleInfo = titleInfo
}
//打开模态窗口
const openAddModal = () => {
  //清空对象内容
  trainRecordInfoAddForm.value = {
    trainInfo: {
      trainId: '',
      trainName: ''
    },
    userInfo: {
      userId: '',
      userName: ''
    },
    // titleInfo: {
    //   titleId: '',
    //   titleName: ''
    // }
    titleIds: ''
  }
  showAddModal.value = true
}
//定义校验规则变量
const ruleFormRef = ref()
const ruleFormModifyRef = ref()
const rules = {
  'trainInfo.trainName': [
    { required: true, message: '训练名称不能为空', trigger: 'change' },
  ],
  'userInfo.userName': [
    { required: true, message: '队员姓名不能为空', trigger: 'change' },
  ],
  // 'titleInfo.titleName': [
  //   { required: true, message: '题目名称不能为空', trigger: 'change' },
  // ],
  titleIds: [
    { required: true, message: '题目名称不能为空', trigger: 'change' },
  ],
}
//发送添加训练记录请求
const addTrainRecordInfo = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      // 解构 trainRecordInfoAddForm.value 中的嵌套属性
      const {
        trainInfo: { trainId, trainName },
        userInfo: { userId, userName },
        // titleInfo: { titleId, titleName }
      } = trainRecordInfoAddForm.value;
      trainRecordInfoAddForm.value.useTitles = 1
      trainRecordInfoAddForm.value.trainId = trainId
      trainRecordInfoAddForm.value.trainName = trainName
      trainRecordInfoAddForm.value.userId = userId
      trainRecordInfoAddForm.value.userName = userName
      if(useTitles.value != 2){
        trainRecordInfoAddForm.value.titleIds = Array.of(trainRecordInfoAddForm.value.titleIds)
      }
      // trainRecordInfoAddForm.value.titleId = titleId
      // trainRecordInfoAddForm.value.titleName = titleName
      console.log(trainRecordInfoAddForm.value)
      // if (useTitles.value == 2) {
      //   // 创建一个数组，将每个 trainId 和其他数据组成一个对象
      //   const trainRankInfo = trainId.map(trainIdItem => ({
      //     userId,
      //     userName,
      //     titleId,
      //     titleName,
      //     trainId: trainIdItem
      //   }));
      //   const res = await trainRecordAddBatchService(trainRecordInfoAddForm.value)
      //   if (res.data.status === 'success') {
      //     await load()
      //     ElMessage.success('批量添加成功')
      //     showAddModal.value = false
      //   } else {
      //     ElMessage.error(res.data.info)
      //   }
      //   return
      // }
      const res = await trainRecordAddBatchService(trainRecordInfoAddForm.value)
      if (res.data.status === 'success') {
        await load()
        ElMessage.success('添加成功')
        showAddModal.value = false
      } else {
        ElMessage.error(res.data.info)
      }
      // const res1 = await trainRankAddService(trainRankInfo)
      // if (res1.data.status !== 'success') {
      //   ElMessage.error(res1.data.info)
      // }

    }
  })
}

/**
 * 修改训练记录信息
 * @type {Ref<UnwrapRef<boolean>, UnwrapRef<boolean> | boolean>}
 */
//修改训练记录（弹出模态窗口）
//定义模态窗口变量和表格对象
const modifyIntroduceModel = ref(false)
const showModifyModal = ref(false)
const trainRecordForm = ref({
  recordId: '',
  trainInfo: {
    trainId: '',
    trainName: ''
  },
  userInfo: {
    userId: '',
    userName: ''
  },
  titleInfo: {
    titleId: '',
    titleName: ''
  }
})
const openModifyModal = (trainRecordInfo) => {
  //将训练记录数据渲染到模态窗口的表格上面
  trainRecordForm.value.recordId = trainRecordInfo.recordId
  trainRecordForm.value.trainInfo.trainId = trainRecordInfo.trainId
  trainRecordForm.value.trainInfo.trainName = trainRecordInfo.trainName
  trainRecordForm.value.userInfo.userId = trainRecordInfo.userId
  trainRecordForm.value.userInfo.userName = trainRecordInfo.userName
  trainRecordForm.value.titleInfo.titleId = trainRecordInfo.titleId
  trainRecordForm.value.titleInfo.titleName = trainRecordInfo.titleName
  //打开模态窗口
  showModifyModal.value = true
}

//发送修改训练记录请求
const handleEdit = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      // 解构 trainRecordForm.value 中的嵌套属性
      const {
        trainInfo: { trainId, trainName },
        userInfo: { userId, userName },
        titleInfo: { titleId, titleName }
      } = trainRecordForm.value;
      trainRecordForm.value.trainId = trainId
      trainRecordForm.value.trainName = trainName
      trainRecordForm.value.userId = userId
      trainRecordForm.value.userName = userName
      trainRecordForm.value.titleId = titleId
      trainRecordForm.value.titleName = titleName
      const res = await trainRecordModifyService(trainRecordForm.value)
      if (res.data.status === 'success') {
        await load()
        ElMessage.success('修改成功')
        showModifyModal.value = false
      } else {
        ElMessage.error(res.data.info)
      }
    }
  })
}

/**
 * 删除训练记录
 */
const openDeleteModal = (recordId) => {
  ElMessageBox.confirm(
    '确定要删除该训练记录吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await trainRecordDeleteService(recordId)
      if (res.data.status === 'success') {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      } else {
        ElMessage({
          type: 'error',
          message: '删除失败',
        })
      }
      await load()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
/**
 * 批量删除训练记录
 */
const openDeleteAllModal = () => {
  //非空判断
  if (selectIds.value == null) {
    ElMessage.info('未选中任何一条训练记录信息')
    return
  }
  if (selectIds.value != null && selectIds.value.length === 0) {
    ElMessage.info('未选中任何一条训练记录信息')
    return
  }
  //批量删除
  ElMessageBox.confirm(
    '确定要删除所有选中的训练记录信息吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await trainRecordDeleteService(selectIds.value)
      if (res.data.status === 'success') {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      } else {
        ElMessage({
          type: 'error',
          message: '删除失败',
        })
      }
      load()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}


</script>

<template>
  <!--  模态窗口-->
  <!--  修改成员信息模态窗口-->
  <div class="modify-modal" v-show="showModifyModal">
    <div class="modify-form">
      <div class="close-btn" @click="showModifyModal = false">&times;</div>
      <h1 style="text-align: center;font-size: 30px">修改训练记录信息</h1>
      <el-form :model="trainRecordForm" ref="ruleFormModifyRef" :rules="rules" label-width="auto"
        style="max-width: 600px;margin: auto;margin-top: 50px">
        <el-form-item label="训练名称" prop="trainInfo.trainName">
          <el-select v-model="trainRecordForm.trainInfo.trainName" clearable placeholder="请查找并选择训练名称"
            style="width: 240px" filterable :remote="true" :remote-method="handleInputTrainChange"
            @change="changeModifytrain" :loading="trainLoading">
            <el-option v-for="(item, index) in trainList" :key="index" :label="item.trainName" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属队员" prop="userInfo.userName" :label-width="80">
          <el-select v-model="trainRecordForm.userInfo.userName" clearable placeholder="请查找并选择所属队员" style="width: 240px"
            filterable :remote="true" :remote-method="handleInputUserChange" @change="changeModifyUser"
            :loading="userLoading">
            <el-option v-for="(item, index) in userList" :key="index" :label="item.name" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="题目名称" prop="titleInfo.titleName" :label-width="80">
          <el-select v-model="trainRecordForm.titleInfo.titleName" clearable placeholder="请查找并选择题目名称"
            style="width: 240px" filterable :remote="true" :remote-method="handleInputtitleChange"
            @change="changeModifytitle" :loading="titleLoading">
            <el-option v-for="(item, index) in titleList" :key="index" :label="item.titleName" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="handleEdit(ruleFormModifyRef)">修改</el-button>
          <el-button @click="showModifyModal = false">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
  <!--  添加训练记录模态窗口-->
  <div class="modify-modal" v-show="showAddModal">
    <div class="modify-form">
      <div class="close-btn" @click="showAddModal = false">&times;</div>
      <h1 style="text-align: center;font-size: 30px">添加训练记录信息</h1>
      <el-form :model="trainRecordInfoAddForm" ref="ruleFormRef" :rules="rules" label-width="auto"
        style="max-width: 600px;margin: auto;margin-top: 50px">
        <el-form-item label="添加训练" style="margin-left: 10px;">
          <el-radio-group v-model="useTitles">
            <el-radio :value="1">单题</el-radio>
            <el-radio :value="2">多题</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="训练名称" prop="trainInfo.trainName">
          <el-select v-model="trainRecordInfoAddForm.trainInfo.trainName" clearable placeholder="请查找并选择训练名称" style="width: 240px"
            filterable :remote="true" :remote-method="handleInputTrainChange"
            @change="changeTrain" :loading="trainLoading">
            <el-option v-for="(item, index) in trainList" :key="index" :label="item.trainName" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属队员" prop="userInfo.userName" :label-width="80">
          <el-select v-model="trainRecordInfoAddForm.userInfo.userName" clearable placeholder="请查找并选择所属队员"
            style="width: 240px" filterable :remote="true" :remote-method="handleInputUserChange" @change="changeUser"
            :loading="userLoading">
            <el-option v-for="(item, index) in userList" :key="index" :label="item.name" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="题目名称" prop="titleIds" :label-width="80">
          <el-select v-model="trainRecordInfoAddForm.titleIds" clearable placeholder="请查找并选择题目名称"
            style="width: 240px" :multiple="useTitles == 2" filterable :remote="true" :remote-method="handleInputtitleChange"
            :loading="titleLoading">
            <el-option v-for="(item, index) in titleList" :key="index" :label="item.titleName" :value="item.titleId" />
          </el-select>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="addTrainRecordInfo(ruleFormRef)">添加</el-button>
          <el-button @click="showAddModal = false">取消</el-button>
        </el-form-item>
      </el-form>

    </div>

  </div>


  <div>
    <!--    功能按钮-->
    <el-card style="width: 36%;margin-bottom: 30px;float: left">
      <el-button @click="openAddModal" type="primary">添加训练记录</el-button>
      <!-- <el-button @click="openDeleteAllModal" type="danger">批量删除</el-button> -->
    </el-card>
    <!--    搜索框-->
    <el-card class="member-search">
      <span style="margin-left: 10px">
        <h1>训练名称：</h1>
      </span>
      <input v-model="trainNameFuzzy" @keyup.enter.native="load">
      <span style="margin-left: 10px">
        <h1>队员姓名：</h1>
      </span>
      <input v-model="userNameFuzzy" @keyup.enter.native="load">
      <span style="margin-left: 10px">
        <h1>题目名称：</h1>
      </span>
      <input v-model="titleNameFuzzy" @keyup.enter.native="load" style="border-right: none;">
      <el-button type="warning" @click="load">搜索</el-button>
    </el-card>
  </div>
  <div>
    <el-table ref="multipleTableRef" :data="trainRecordInfo" stripe style="width: 100%;margin-top: 30px"
      @selection-change="handleSelectionChange">
      <el-table-column width="55" />
      <el-table-column property="trainName" label="训练名称" width="170" />
      <el-table-column property="userName" label="队员姓名" width="170">
      </el-table-column>
      <el-table-column property="titleName" label="题目名称" width="170" />
      <el-table-column property="createTime" label="创建时间" />
      <el-table-column property="updateTime" label="修改时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" type="info" @click="openModifyModal(scope.row)">
            修改
          </el-button>
          <el-button size="small" type="danger" @click="openDeleteModal(scope.row.recordId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页组件-->
    <el-card style="margin-top: 20px;float: right;">
      <div class="demo-pagination-block">
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[2, 5, 10, 20]"
          size="large" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @current-change="handleCurrentChange" @size-change="handleSizeChange" />
      </div>
    </el-card>

  </div>
</template>


<style scoped>
/*模态窗口样式*/
.modify-modal {
  position: fixed;
  z-index: 10;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: black;
  opacity: 1;
}

/*模态窗口表格样式*/
.modify-form {
  background-color: #ffffff;
  margin: 5% auto;
  /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  z-index: 10;
  border-radius: 10%;
  width: 30%;
  /* Could be more or less, depending on screen size */
}

.close-btn {
  cursor: pointer;
  color: #000000;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

/*搜索样式*/
.member-search {
  width: 61%;
  float: right
}

.member-search span {
  float: left;
}

.member-search input {
  float: left;
  height: 20px;
  width: 15%;
  border: solid 2px;
  margin-top: 2px;
}

/*表头样式*/
:deep() th.el-table__cell {
  color: black;
  font-size: 15px;
}
</style>
